package com.gxa.user.utils;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;

import com.gxa.user.config.SmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Random;
import java.util.Set;

/**
 * 发送短信的工具类
 * @author 阔爱又迷人的川锅锅呀
 */
@Component
public class SmsUtil {


    @Autowired
    private SmsConfig config;

    /**
     * 发送短信的方法
     * @param phone
     * @return
     */
    public Boolean sendMessage(String phone, String code){
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(config.getServerIp(), config.getServerPort());
        sdk.setAccount(config.getAccountSId(), config.getAccountToken());
        sdk.setAppId(config.getAppId());
        sdk.setBodyType(BodyType.Type_JSON);
        String to = phone;
        String templateId= config.getTemplateId();
        String[] datas = {code,"2"};
        HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for(String key:keySet){
                Object object = data.get(key);
                System.out.println(key +" = "+object);
            }
            return true;
        }else{
            //异常返回输出错误码和错误信息
            System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
        }

        return false;
    }


    /**
     * 获取随机验证码
     * @return
     */
    public String getCode(){
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 4; i++) {
            int rand = random.nextInt(10);
            code += rand;
        }
        return code;
    }





}
